<?php
namespace Modules\Activity\Http\Controllers\Admin\Fudai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Fudai\Activity;
// use \Modules\Activity\Entities\ActivityRecord;
use Setting;

use Validator;
use ThrowException;
use DB;
use Cache;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
            // 'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = ['list_weight' => 'desc'];
        // $options['with_count'] = ['records', 'skus'];
        // $options['with'] = ['activity_info'];
        $optoins['with'] = ['skus'];

        $options['only'] = [
            'id',
            'uuid',
            'created_at',
            'detail_images',
            'images',
            'title',
            'money_price',
            'score_price',
            'sku_level',
            'stock',
            'sales',
            'status',
            'union_status_text',
            'union_status',
            'thumb',
            'list_weight'
        ];

        $list = Activity::getList($options);

        // sku_level 进行全局替换
        $globalSetting = @Setting::get('sys_fudai_sku_level')['list'];

        $list->each(function ($item) use ($globalSetting) {
            $item->sku_stock = $item->skus()->sum('stock');

            $skus = $item->skus;
            $skuLevel = $item->sku_level; 

            for ($i=1; $i<=6; $i++)
            {
                $skuLevel[$i - 1]['sku_total'] = $skus->where('level', $i)->count();
                $skuLevel[$i - 1]['sku_sales'] = $skus->where('level', $i)->sum('sales');
                $skuLevel[$i - 1]['sku_stock'] = $skus->where('level', $i)->sum('stock');

                $skuLevel[$i - 1]['title'] = @$skuLevel[$i - 1]['title'] ?: @$globalSetting[$i - 1]['title'];
            }

            $item->sku_level = $skuLevel;

        });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        // 
        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'title' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();


        DB::beginTransaction();

        $info['sku_level'] = [
            [
                'status' => 1,
                'odds' => 20
            ],
            [
                'status' => 1,
                'odds' => 20
            ],
            [
                'status' => 1,
                'odds' => 20
            ],
            [
                'status' => 1,
                'odds' => 20
            ],
            [
                'status' => 1,
                'odds' => 20
            ],
        ];

        $item = Activity::create($info);

        DB::commit();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            $item->update($info);
        }

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }

    public function updateSkuLevel(Request $req, $uuid)
    {
        $rule = [
            'list' => ['required', 'array']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $list = $req->input('list');

        if (count($list) === 6) {
            unset($list[5]);
        }

        $item->update([
            'sku_level' => $list
        ]);

        return [];
    }

    public function testLottery(Request $req, $uuid)
    {
        $rule = [
            'total' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        if (Cache::get('fudai_test_lottery_' . $item->uuid))
        {
            // ThrowException::Conflict('此活动另外一个测试进程进行中~');
        }

        Cache::put('fudai_test_lottery_' . $item->uuid, true, 3000);

        $total = $req->total;

        while ($total > 0) {
            $times = $total <= 4 ? $total : rand(1, 4);

            $item->pickLuckySkus($times);

            $item->addSales($times);

            // 刷新
            $item = Activity::getEntity([
                'uuid' => $uuid
            ]);

            // 基础款是否已售空
            if ($item->skus->where('level', 1)->sum('stock') <= 0) {
                ThrowException::Conflict('此款基础款包已售罄, 无法继续测试~');
            }

            $total -= $times;
        }

        Cache::put('fudai_test_lottery_' . $item->uuid, false, 600);

        return [];
    }

    // 复杂一个活动
    public function copy(Request $req, $uuid)
    {

        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo([
            'image_3d',
            'invite_rule',
            'is_invite_enabled',
            'min_lucky_score',
            'money_price',
            'multi_buy_discount',
            'tags',
            'thumb',
            'title',
            'sku_level'
        ]);

        $info['title'] .= '(副本)';
        $info['status'] = 0;

        $newItem = Activity::create($info);

        $skuArray = [];
        foreach ($item->skus as $sku) {
            $sku->stock = $sku->stock + $sku->sales;

            $skuInfo = $sku->getInfo([
                'activity_id',
                'sku_type',
                'assets',
                'product_id',
                'title',
                'number',
                'thumb',
                'money_price',
                'score_price',
                'stock',
                'odds',
                'level',
                'list_weight',
                'status',
                'is_resaleable',
                'display_money_price',
                'discount_score_price',
                'detail_images',
                'use_lucky_score'
            ]);

            $skuInfo['uuid'] = uniqid();

            array_unshift($skuArray, $skuInfo);
        }

        $newItem->skus()->createMany($skuArray);

        $newItem->updateStock();

        return [];
    }

}
